﻿using System.Collections.Generic;
using Foundation;
using Newtonsoft.Json;

namespace SoulCard
{
    public class CachedCardDatas
    {
        public List<CardData> CardDatas = new List<CardData>();

        private static CachedCardDatas mCachedCardDatas;

        public static CachedCardDatas Get()
        {
            var savedJsonContent = NSUserDefaults.StandardUserDefaults.StringForKey("saved_data");

            return mCachedCardDatas ?? (mCachedCardDatas = string.IsNullOrEmpty(savedJsonContent) ? new CachedCardDatas() :
                                        JsonConvert.DeserializeObject<CachedCardDatas>(savedJsonContent));
        }

        public void Save()
        {
            NSUserDefaults.StandardUserDefaults.SetString(JsonConvert.SerializeObject(this), "saved_data");

        }

        /// <summary>
        /// 这个是用来接收网络请求的结果用的
        /// </summary>
        /// <param name="cardDatas">Card datas.</param>
        public void Save(List<CardData> cardDatas)
        {
            if (!AreEqual(CardDatas, cardDatas))
            {
                CardDatas = cardDatas;

                Save();
            }
        }

        private static bool AreEqual(List<CardData> cardDatas, List<CardData> remoteCardDatas)
        {
            if (cardDatas.Count != remoteCardDatas.Count) return false;

            cardDatas.Sort((a, b) => a.Id.ToInt() - b.Id.ToInt());
            remoteCardDatas.Sort((a, b) => a.Id.ToInt() - b.Id.ToInt());

            for (var i = 0; i < cardDatas.Count; i++)
            {
                if (cardDatas[i].Complete != remoteCardDatas[i].Complete) return false;
                if (cardDatas[i].Content != remoteCardDatas[i].Content) return false;
                if (cardDatas[i].SetTop != remoteCardDatas[i].SetTop) return false;
                if (cardDatas[i].CreatedAt != remoteCardDatas[i].CreatedAt) return false;
                if (cardDatas[i].ModifiedAt != remoteCardDatas[i].ModifiedAt) return false;
            }

            return true;
        }
    }

    public static class IntExtension
    {
        public static int ToInt(this string selfStr,int defaultValue = 0)
        {
            return int.TryParse(selfStr, out int retValue) ? retValue : defaultValue;
        }
    }
}
